package jsu.hx.lost.exception;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jsu.hx.lost.Mapper.FindMapper;
import jsu.hx.lost.Mapper.LostMapper;
import jsu.hx.lost.Model.entity.FindItem;
import jsu.hx.lost.Model.entity.LostItem;
import jsu.hx.lost.Model.entity.Notifications;
import jsu.hx.lost.Model.event.ItemCreatedEvent;
import jsu.hx.lost.Service.NotificationsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class ItemMatchHandler {

    @Autowired
    private LostMapper lostItemMapper;

    @Autowired
    private FindMapper findItemMapper;

    @Autowired
    private NotificationsService notificationsService;

    @EventListener
    @Transactional
    public void handleItemCreatedEvent(ItemCreatedEvent<?> event) {
        if (event.getItemType().equals("LOST")) {
            // 处理失物记录，查找招领匹配
            LostItem lostItem = (LostItem) event.getItem();
            checkFindItemMatches(lostItem);
        } else {
            // 处理招领记录，查找失物匹配
            FindItem findItem = (FindItem) event.getItem();
            checkLostItemMatches(findItem);
        }
    }

    // 查找招领匹配
    private void checkFindItemMatches(LostItem lostItem) {
        QueryWrapper<FindItem> query = new QueryWrapper<>();
        query.eq("item_category", lostItem.getItemCategory())
                .eq("item_name", lostItem.getItemName())
                .apply("found_time >= {0}", lostItem.getLostTime()) // 招领时间晚于丢失时间
                .eq("is_deleted", 0);

        findItemMapper.selectList(query).forEach(findItem -> {
            createNotification(
                    findItem.getUserId(), // 通知招领发布者
                    lostItem.getUserId(), // 失主
                    "LOST",
                    lostItem.getId(),
                    findItem.getId(),
                    "您发布的招领信息可能有匹配的失主"
            );
        });
    }

    // 查找失物匹配
    private void checkLostItemMatches(FindItem findItem) {
        QueryWrapper<LostItem> query = new QueryWrapper<>();
        query.eq("item_category", findItem.getItemCategory())
                .eq("item_name", findItem.getItemName())
                .apply("lost_time <= {0}", findItem.getFoundTime()) // 丢失时间早于招领时间
                .eq("is_deleted", 0);

        lostItemMapper.selectList(query).forEach(lostItem -> {
            createNotification(
                    lostItem.getUserId(), // 通知失主
                    findItem.getUserId(), // 招领发布者
                    "FOUND",
                    findItem.getId(),
                    lostItem.getId(),
                    "您发布的失物可能有匹配的招领信息"
            );
        });
    }

    private void createNotification(Long receiverId, Long relatedUserId,
                                    String relatedType, Long relatedItemId,
                                    Long oppositeItemId, String content) {
        Notifications notification = Notifications.builder()
                .userId(receiverId)
                .title("物品匹配通知")
                .content(content)
                .relatedType(relatedType)
                .relatedLostItemId(relatedType.equals("LOST") ? relatedItemId : oppositeItemId)
                .relatedFoundItemId(relatedType.equals("FOUND") ? relatedItemId : oppositeItemId)
                .build();

        notificationsService.save(notification);
    }
}
